﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Routing;
using System.Collections.Specialized;

using Microsoft.Practices.Unity;

using ERPStore.Services;

using ERPStore.Extensions;

using ERPStore.Web.Extensions;
using ERPStore.Web.Html;

using CloudSoft.Extensions;

namespace ERPStore.Web.Controllers
{
	public partial class CatalogController
	{

		[ActionFilters.TrackerActionFilter]
		public ActionResult CategoryList()
		{
			var list = CatalogService.GetCategories().OrderBy(i => i.Name).ToList();
			ViewData.Model = list;
			return View();
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult Category(string link)
		{
			if (link.IsNullOrEmpty())
			{
				Logger.Warn("Category page without link");
				return RedirectToERPStoreRoute(ERPStore.Web.Routing.ERPStoreRoutes.PRODUCT_CATEGORIES);
			}

			link = link.Trim().TrimEnd('/');
			var category = CatalogService.GetCategoryByLink(link);
			if (category == null)
			{
				var recoveredCategory = RewriterService.RecoverableProductCategory(link);
				if (recoveredCategory != null)
				{
					var url = Url.ProductCategoryHref(recoveredCategory.Code);
					return RedirectPermanent(url);
				}
				return RewriterService.RewriteUrl(Request);
			}

			var filter = CatalogService.CreateProductListFilter(this.HttpContext.GetWebContextParameterList());
			filter.ProductCategoryId = category.Id;
			filter.SortByScore = false;

			var result = GetProductList(filter);

			// Dans le cas ou le numéro de page n'exise plus
			// On retourne sur la premiere page 
			if (result != null
				&& result.Count == 0
				&& result.PageIndex > 1)
			{
				var url = Request.RawUrl.RemoveParameter(ERPStore.GlobalConfiguration.Configuration.Settings.Catalog.PageParameterName);
				return Redirect(url);
			}

			if (result != null
				&& result.Count == 0)
			{
				return RewriterService.RewriteProductCategoryUrl(category, Url);
			}

			result.Category = category;
			result.ListType = ERPStore.Models.ProductListType.Category;
			ViewData.Model = result;
			ViewBag.ProductListFilter = filter;

			EventPublisherService.PublishAsync(new Events.ProductListEvent(User, result, ERPStore.Models.ProductListType.Category));

			return View();
		}

		// ?
		public ActionResult ShowProductCategoryByCode(string viewName, string categoryCode)
		{
			var category = CatalogService.GetCategoryByCode(categoryCode);
			return PartialView(viewName, category);
		}

		#region Partial Rendering

		[OutputCache(Duration=3600,VaryByParam="*")]
		public ActionResult ShowCategoriesBox(string viewName)
		{
			var list = CatalogService.GetCategories();
			return PartialView(viewName, list);
		}

		public ActionResult ShowCategorieListForefront(string viewName, System.Web.Routing.RouteData routeData)
		{
			var list = CatalogService.GetForefrontCategories();
			return PartialView(viewName, list);
		}

		public ActionResult ShowProductCategoryListByBrand(ERPStore.Models.Brand brand, string viewName)
		{
			var searchFilter = CatalogService.CreateProductListFilter(HttpContext.GetWebContextParameterList());

			searchFilter.BrandId = brand.Id;

			// var list = CatalogService.GetProductCategoryListByBrandId(brand.Id);
			var list = CatalogService.GetProductCategoryListBySearch(searchFilter);
			ViewData.Model = list;
			return PartialView(viewName);
		}

		public ActionResult ShowProductCategoryListBySearch(string viewName, string search)
		{
			if (!search.IsNullOrTrimmedEmpty())
			{
				search = search.Trim();
			}

			var searchFilter = CatalogService.CreateProductListFilter(HttpContext.GetWebContextParameterList());
			searchFilter.Search = search;

			var list = CatalogService.GetProductCategoryListBySearch(searchFilter);
			ViewData.Model = list;
			return PartialView(viewName);
		}

		public ActionResult ShowFilteredProductCategoryListByProductList(string viewName, string filter, string currentUrl)
		{
			if (viewName.IsNullOrTrimmedEmpty()
				|| filter.IsNullOrTrimmedEmpty())
			{
				return new EmptyResult();
			}

			var jsonfilter = filter.UnGZipFromBase64String();
			var f = jsonfilter.FromJSon<ERPStore.Models.ProductListFilter>();
			if (f.ProductCategoryId.HasValue)
			{
				f.ProductCategory = CatalogService.GetCategoryById(f.ProductCategoryId.Value);
			}

			currentUrl = currentUrl ?? string.Empty;
			ViewBag.CurrentUrl = currentUrl.Replace("&amp;", "&");
			var parameters = new Uri("http://url" + currentUrl).GetParameters();
			ViewBag.Parameters = parameters;
			ViewBag.CurrentFilter = f;

			var key = string.Format("categorylistfilter:{0}:{1}:{2}", filter, viewName, currentUrl);
			var list = CacheService[key] as IList<ERPStore.Models.ProductCategory>;
			if (list == null)
			{
				list = CatalogService.GetProductCategoryListBySearch(f);
				CacheService.Add(key, list, DateTime.Now.AddHours(1));
			}
			ViewData.Model = list;
			return PartialView(viewName);
		}

		public ActionResult ShowProductCategoryListByProductList(ERPStore.Models.ProductListFilter filter, string viewName)
		{
			if (!filter.Search.IsNullOrTrimmedEmpty())
			{
				filter.Search = filter.Search.Trim();
			}

			var list = CatalogService.GetProductCategoryListBySearch(filter);
			ViewData.Model = list;
			return PartialView(viewName);
		}

		// Moteurs de recherche
		public ActionResult ShowSubCategories()
		{
			return new EmptyResult();
		}

		[HttpPost]
		public ActionResult ShowSubCategories(string productCategoryCode, string viewName)
		{
			var category = CatalogService.GetCategories().DeepFirst(i => i.Code == productCategoryCode);

			if (category == null)
			{
				return new EmptyResult();
			}
			ViewData.Model = category;
			return PartialView(viewName);
		}

		#endregion


	}
}
